<?php
namespace Tongcheng\Controller;
use Think\Controller;

/**
 * Class ShetuanBackController
 * @package Tongcheng\Controller
 *
 * 社团管理
 */
class ShetuanBackController extends CommonController {
    /**
     * 获取社团列表
     */
    public function index(){

        $model = M("Shetuan");
        $map = array();
        // $map['is_pay'] = 1;
        //社团分类  1书评2话题3问答4写文
        $type = $_GET['type']?$_GET['type']:1;
        $map['type'] = $type;
        $res['count'] = $model->where($map)->count();
        $page = $_GET['page']?$_GET['page']:1;
        $limit = $_GET['limit']?$_GET['limit']:10;
        $list = $model->field("tp_shetuan.*,s.nickname,FROM_UNIXTIME(tp_shetuan.add_time,\"%m-%d %H:%i\") time")->join("tp_member s on s.uid = tp_shetuan.uid",'left')->where($map)->page("{$page},{$limit}")->order('id desc')->select();
        $list = $this->isDianZan($list);
        $res['list']= $list;
        $res['type'] = $type;
        if(IS_AJAX){
            $this->ajaxReturn($res);
        }else{
            $this->assign('res', $res);
            $this->display();
        }
    }

    /**
     * 查看社团信息
     */
    public function edit(){
        $model = M("Shetuan");
        $id = $_GET['id'];
        $list = $model->field('tp_shetuan.*, tp_member.*,FROM_UNIXTIME(tp_shetuan.add_time,"%m-%d %H:%i") time')->join('tp_member on tp_shetuan.uid = tp_member.uid','left')->where('tp_shetuan.id = '.$id)->find();
        $countList = $model->query('select * from tp_dianzan_log dl where dl.otherid = '.$id.' and dl.from = '.(intval($list['type'])+2));
        if(!empty($countList)){
            $dianzancount = count($countList);
        }
        $list['dianzan_num'] = $dianzancount;
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 删除社团信息
     */
    public function del(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $result = M('Shetuan')->where('id = '.$id)->delete();
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }


    //判断是否点赞，并返回新的数据
    public function isDianZan($list){
        $model = M('');
        $newList = array();

        foreach ($list as $key=>$item){
            if(!empty($item)){
                $dianzancount = 0;
                //获取点赞数目
                $countList = $model->query('select * from tp_dianzan_log dl where dl.otherid = '.$item['id'].' and dl.from = '.(intval($item['type'])+2));
                if(!empty($countList)){
                    $dianzancount = count($countList);
                }
                $item['dianzan_num'] = $dianzancount;
                array_push($newList,$item);
            }
        }
        return $newList;
    }

}